<?php

namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Session;

class WechatController extends BaseController
{
    //定义一个属性用来回复文本消息
    protected $xmlTextSql = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";

    /**
     * 测试连接微信服务器是否成功 并且分别判断get post 请求
     * @param Request $request
     * @return bool
     */
    public function check(Request $request)
    {
        //当微信服务器中返回的是get请求
        if ($request->isMethod('GET')) {
            $signature = $request->get('signature');
            $timestamp = $request->get('timestamp');
            $nonce = $request->get('nonce');
            $tmpArr = array('fengwei', $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                echo $request->get('echostr');
                die();
            } else {
                return false;
            }
        }
        //当微信服务器中返回的是post请求
        if ($request->isMethod('POST')) {
            //如果是post请求 微信服务器传过来的数据是xml 获取请求原始数据流
            $xmlData = file_get_contents("php://input");
            Cache::put('fw', $xmlData);
            //原始的数据流传递到将xml文件转为数组的方法当中
            $data = $this->xmlToArray($xmlData);
            //判断微信服务器传递过来的参数里的MsgType为什么类型 然后选择返回类型
            switch ($data['MsgType']) {
                case 'text':
                {
                    //因为MsgType为text类型 所以返回到replyText方法当中
                    $this->replyText($data);
                }
                case 'event':
                {
                    //因为MsgType为类型event 所以返回到replyEvent方法当中
                    $this->replyEvent($data);
                }

            }
        }
    }
    /**
     * 接收微信服务器传递过来的信息
     */
    public function getsession()
    {
        $xml = Cache::get('fw');
        $data = $this->xmlToArray($xml);
        print_r($data);
        die();
    }
    /**
     * 把xml格式的数据转换为数组
     * @param string $xml
     * @return array
     */
    public function xmlToArray($xml = "")
    {
        return (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    }
    /**
     * 关注自动回复
     * @param $data
     */
    public function replyEvent($data)
    {
        if ($data['Event'] == 'subscribe') {
            $xmlEventSql = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[event]]></MsgType>
                <Content><![CDATA[%s]]></Content>
            </xml>";
            $sql = sprintf($xmlEventSql, $data['FromUserName'], $data['ToUserName'], time(), '感谢你的关注么么呢么么么么打');
            echo $sql;
            die();
        }
    }

    /**
     * 文本自动回复
     */
    public function replyText($data)
    {
        if ($data['Content'] == '你好') {
            $content = '我还要补充一句，今天的你也很帅！';
        } elseif ($data['Content'] == '神秘人') {
            $content = '你也很帅，我亲爱的神秘人';
        } elseif ($data['Content'] == '神秘人') {
            $content = '爱神秘人';
        } elseif ($data['Content'] == '图片') {

            $tr="<xml>
                        <ToUserName><![CDATA[%s]]></ToUserName>
                        <FromUserName><![CDATA[%s]]></FromUserName>
                        <CreateTime>%s</CreateTime>
                        <MsgType><![CDATA[image]]></MsgType>
                        <Image>
                            <MediaId><![CDATA[%s]]></MediaId>
                        </Image>
                    </xml>";

            $tr=sprintf($tr,$data['FromUserName'],$data['ToUserName'],time(),"wr4qpotuHrpei4_mTQgLAr755AwwOhHZyNFTfdhPysMNWHUjPUHc-poSOe4GDw13");
            print_r($tr);die;
        }
        //填写参数
        $sql = sprintf($this->xmlTextSql, $data['FromUserName'], $data['ToUserName'], time(), $content);
        //进行输出
        echo $sql;
        die();
    }

    /**
     * 上传图片
     */
    public function uploadimg(){
        $url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=image";
        $url=sprintf($url,$this->getToken());
//        print_r($url);
        $file="/www/wwwroot/fw/www.fengwei.ink/public/images/1.jpg";
        $data=$this->httpPost($url,$file);
        print_r($data);
    }

    public function httpPost($url, $data){
        $ch = curl_init();
        if (class_exists('\CURLFile')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
            $data = array('media' => new \CURLFile($data));//>=5.5
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
            $data = array('media' => '@' . realpath($data));//<=5.5
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "TEST");
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }



    /**
     * 获取access_token
     */
    public function getAccessToken(){
        $appid="wxb536810ec2b4dca5";
        $secret="e076733b8e7e38cac41bad1d41de8f87";
        $sql="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        $curl=sprintf($sql,$appid,$secret);
        $curl=file_get_contents($curl);
        $curl=json_decode($curl,true);
        $token=$curl['access_token'];
        return $token;
    }
    public function pushMaster(){
        $sql="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
        $curl=sprintf($sql,$this->getAccessToken());
        $data= [
            "touser"=>"o63rP6rUK85TxCs47U0DNcGid43Q",
            "template_id"=>"kUEaApqHYvR3TUvm8VFpH2RloTttJdv9XTtC-x3fgrs",
            "data"=>[
                "order_no"=>[
                    "value"=>1,
                ],
                'total_price'=>[
                    'value'=>2
                ]
            ]
        ];
        $curl=$this->posturl($curl,$data);

        print_r($curl);die();

    }

}














